package be.idamf.profiler
{
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;
	
	public class InstanceMonitor
	{
		protected static const REF:Dictionary = new Dictionary(true);
		protected static const INS:Object = {};
		
		public static function track(instance:Object):void
		{
			var name:String;
			
			name = getQualifiedClassName(instance);
			
			if (!INS[name])
				INS[name] = 1;
			else
				INS[name] = INS[name] + 1;
			
			REF[instance] = INS[name];
		}
		
		public static function getTotalInstances(kind:Class):int
		{
			var name:String;
			
			name = getQualifiedClassName(kind);
			
			if (!INS[name])
				return 0;
			
			return int(INS[name]);
		}
		
		public static function getAliveInstances(kind:Class):int
		{
			var name:String;
			var ref:Object;
			var n:int = 0;
			
			name = getQualifiedClassName(kind);
			
			for (ref in REF)
			{
				if (getQualifiedClassName(ref) == name)
				{
					++n;
				}
			}
			
			return n;
		}
		
		public static function getDeadInstances(kind:Class):int
		{
			return getTotalInstances(kind) - getAliveInstances(kind);
		}
		
		public static function stats():Array
		{
			var instances:Object = {};
			var name:String;
			var ref:Object;
			var stats:Array = [];
			
			for (name in INS)
				instances[name] = [];
			
			for (ref in REF)
				(instances[getQualifiedClassName(ref)] as Array).push(REF[ref]);
			
			for (name in INS)
				stats.push({name:name, instances:instances[name], total:INS[name], alive:(instances[name] as Array).length});
			
			return stats;
		}
	}
}